//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class MulRKRecord : WorksheetLevelRecord
    {
        private readonly List<Pair<ushort, RKNumber>> records = new List<Pair<ushort, RKNumber>>();
        private ushort firstColumnIndex;
        private ushort lastColumnIndex;

        private ushort rowIndex;

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.MulRk; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.Write(rowIndex);
            context.Write(firstColumnIndex);
            foreach (var record in records)
            {
                context.Write(record.First);
                record.Second.Write(context.Writer);
            }
            context.Write(lastColumnIndex);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            rowIndex = context.ReadUInt16();
            firstColumnIndex = context.ReadUInt16();
            int count = length - 6;
            count = count/6;
            for (int i = 0; i < count; i++)
            {
                ushort xfid = context.ReadUInt16();
                var rkValue = new RKNumber();
                rkValue.Read(context.Reader);
                records.Add(new Pair<ushort, RKNumber>(xfid, rkValue));
            }
            lastColumnIndex = context.ReadUInt16();
        }

        internal override void Apply(BiffReaderWorksheetContext context)
        {
            int col = firstColumnIndex;
            foreach (var v in records)
            {
                Cell c = context.Worksheet.EnsurePromotedCell(rowIndex, col);
                c.SetFormattingRecordUnsafe(context.WorkbookContext.GetCellFormattingRecord(v.First));
                c.Value = (double)v.Second;
                col++;
            }
        }
    }
}